import AsyncStorage from '@react-native-community/async-storage';

import { getUserInfo } from '../../../store/user';
import { emitUpdateCoinProgress } from '../event';
import { CLASS_ROOM_STORAGE_KEY_COIN_PROGRESS, UserRole } from '../constant';

let coinProgress = 0;
let timer: NodeJS.Timer | null;
let isStopTimer = false;

const MAX_COIN_PROGRESS_NUMBER = 60 * 1000;

AsyncStorage.getItem(CLASS_ROOM_STORAGE_KEY_COIN_PROGRESS).then(
  (res: any): void => {
    if (res) {
      const progress = JSON.parse(res);
      coinProgress = Number(progress);
    }
  }
);

interface UpdateCoinProgressData {
  progress: number;
  isStop?: boolean;
  animatedEnd?: () => void;
}

export const clearCoinProgressTimer = (): void => {
  isStopTimer = false;
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
};

export const updateCoinProgress = ({
  progress,
  isStop = false,
  animatedEnd
}: UpdateCoinProgressData): void => {
  emitUpdateCoinProgress({
    progress,
    canAddCoin: progress === 10,
    isStop,
    animatedEnd
  });
  AsyncStorage.setItem(
    CLASS_ROOM_STORAGE_KEY_COIN_PROGRESS,
    JSON.stringify(progress)
  );
};

export const clearCoinProgress = (): void => {
  clearCoinProgressTimer();
  coinProgress = 0;
  updateCoinProgress({ progress: 0 });
};

export const stopCoinProgressTimer = (): void => {
  if (isStopTimer) return;
  isStopTimer = true;
  updateCoinProgress({ progress: coinProgress, isStop: true });
};

export const cancelStopProgressTimer = (): void => {
  if (!isStopTimer) return;
  isStopTimer = false;
  updateCoinProgress({ progress: coinProgress, isStop: false });
};

export const startCountCoinProgress = (): void => {
  const { role } = getUserInfo();
  const isParent = role === UserRole.Parent;

  if (isParent) return;

  if (timer) return;

  timer = setInterval((): void => {
    if (isStopTimer) return;
    coinProgress += 1;
    if (coinProgress >= 10) {
      coinProgress = 0;
    }
    if (coinProgress === 0) {
      updateCoinProgress({
        progress: 10,
        animatedEnd: (): void => {
          updateCoinProgress({ progress: coinProgress });
        }
      });
      return;
    }
    updateCoinProgress({ progress: coinProgress });
  }, MAX_COIN_PROGRESS_NUMBER);
};

export const getCoinProgress = (): number => {
  return coinProgress;
};

export const setCoinProgress = (progress: number): void => {
  coinProgress = progress;
  updateCoinProgress({ progress });
};
